<?php
/**
 * 评价 百分比
 */

namespace PKApp\Form;

use PKApp\Form\Classes\TraitFrom;
use PKApp\Site\Classes\SiteController;
use PKFrame\DataHandler\Arrays;

class ApiGetRatingData extends SiteController
{

    use TraitFrom;

    public function __construct()
    {
        $this->getFieldByOption();
    }

    public function Main()
    {
        $dir = 'RatingData';
        $field = request()->get('name');
        $file_name = date('Ymd') . '_' . $field . $this->id_form;
        $params = [];
        if (!empty($this->serviceForm()->restrictField)) {
            $restrictField_value = Arrays::GetKey('restrictField_value', request()->get(), 'Empty_restrictFieldVal');
            $file_name .= '_' . $restrictField_value;
        }
        $cache_data = cache()->Tmp()->ReadByJSON($file_name, $dir);
        if (!empty($cache_data)) {
            $this->json($cache_data);
        }
        if (!array_key_exists($field, $this->listField_option)) {
            $this->noticeByJson('ModelField_option_Empty', 'model');
        }
        if (isset($restrictField_value)) {
            $params = $this->getFieldByRestrict($restrictField_value);
        }
        $db_res = $this->serviceForm()->GetGradeCount($field, $params);
        $grade_data = Arrays::Column($db_res, 'count', $field);
        $total = 0;
        foreach ($db_res as $item) {
            $total += $item['count'];
        }
//         获取选项数据
        $result = [];
        foreach ($this->listField_option[$field] as $index_id => $item_name) {
            $tmp_size = array_key_exists($index_id, $grade_data) ? $grade_data[$index_id] : 0;
            $result[] = [
                'id' => $index_id,
                'name' => $item_name,
                'size' => $tmp_size,
                'ratio' => $total > 0 ? round($tmp_size / $total * 100, 2) : 0,
            ];
        }
        cache()->Tmp()->WriteByJSON($file_name, $result, $dir);
        $this->json($result);
    }

}
